﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;


namespace NaCl.OneDayThreeRate.Parser
{
    public class jujuparser
    {

        HttpWebResponse resp = null;
        HttpWebRequest req = null;
        string searchUrl = "http://www.jesseclub.com/bbs/zboard.php?id=club2";
        Dictionary<string, ListViewItem> dicItem = new Dictionary<string, ListViewItem>();
        enum Column
        {
            종목 = 0,
            수량,
            매수가,
            매도가,
            손절가
        }

        private void todayLink()
        {
            HttpWebResponse respBuffer = resp;

            //로그인 (사용자 인증 후에 할 일)

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(searchUrl);

            //세션 쿠키 유지

            req.CookieContainer = new CookieContainer();

            req.CookieContainer.Add(respBuffer.Cookies);

            respBuffer = (HttpWebResponse)req.GetResponse();

            TextReader re = (TextReader)new StreamReader(respBuffer.GetResponseStream(), Encoding.GetEncoding("EUC-KR"));

            string strHtml = re.ReadToEnd();

            Regex r;
            Match m;
            // ref. url http://phpschool.com/gnuboard4/bbs/board.php?bo_table=tipntech&wr_id=32231
            string pattern = string.Empty;

            pattern += "<a href=\"?(?<url>.*?)\"?.*?>(?<text>.*?)</a>";
            r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            bool flag = false;
            for (m = r.Match(strHtml); m.Success; m = m.NextMatch())
            {
                if (m.Groups[0].Value.Contains(DateTime.Now.ToString("dd") + "일") && m.Groups[0].Value.Contains("추천"))
                {
                    pattern = @"([0-9a-z-]+(\.[_0-9a-z-]+)+(:[0-9]{2,4})?\/?)";    // domain+port
                    pattern += @"([\.~_0-9a-z-]+\/?)*";  // sub roots or sub directory
                    pattern += @"(\S+\.[_0-9a-z]+)?"; // file & extension string
                    pattern += @"\?([_0-9a-z#&=-]+)*";     // parameter
                    r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    searchUrl = "http://www.jesseclub.com/bbs/" + r.Match(m.Groups[0].Value).Groups[0].Value;
                    //DateTime.Now.ToString("DD") 
                    flag = true;
                    break;
                }
            }
            if (flag) parsingData();
            else MessageBox.Show("추천주 항목이 없습니다");
        }

        private void parsingData()
        {
            string htmlBuffer = "";

            HttpWebResponse respBuffer = resp;


            //로그인 (사용자 인증 후에 할 일)

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(searchUrl);

            //세션 쿠키 유지

            req.CookieContainer = new CookieContainer();

            req.CookieContainer.Add(respBuffer.Cookies);

            respBuffer = (HttpWebResponse)req.GetResponse();

            TextReader r = (TextReader)new StreamReader(respBuffer.GetResponseStream(), Encoding.GetEncoding("EUC-KR"));

            htmlBuffer = r.ReadToEnd();


            htmlBuffer = htmlBuffer.Substring(htmlBuffer.IndexOf("의견"));
            htmlBuffer = Regex.Replace(htmlBuffer, @"<(.|\n)*?>", String.Empty);
            htmlBuffer = Regex.Replace(htmlBuffer, @"&nbsp(;)*", String.Empty);
            htmlBuffer = htmlBuffer.Replace(" ", "").Replace("\t", "").Replace("//-->", "");

            String[] str = htmlBuffer.Split(new Char[] { '\n' });

            htmlBuffer = null;
            selList.Items.Clear();
            buyList.Items.Clear();
            alertList.Items.Clear();

            string temp = "";
            int byuItemCnt = 0;




            foreach (String s in str)
            {
                temp = s.Trim();
                if ((temp.Contains("매도") && temp.Contains("▶")) || temp.Contains("1차목표가돌파") || temp.Contains("상한가"))
                    selList.Items.Add(s);
                else if (temp.Contains("손절가") && temp.Contains("▶"))
                {
                    if (dicItem.Keys.Contains(findItem(temp)) == false)
                    {
                        ListViewItem item = new ListViewItem();
                        item.Text = findItem(temp);

                        ListViewItem.ListViewSubItem subitem = new ListViewItem.ListViewSubItem();
                        subitem.Text = "10";
                        item.SubItems.Add(subitem);

                        subitem = new ListViewItem.ListViewSubItem();
                        subitem.Text = findBuyPrice(temp);
                        item.SubItems.Add(subitem);

                        subitem = new ListViewItem.ListViewSubItem();
                        subitem.Text = findSellPrice(temp);
                        item.SubItems.Add(subitem);

                        subitem = new ListViewItem.ListViewSubItem();
                        int sellPrice = (int)(int.Parse(item.SubItems[(int)Column.매수가].Text) * 0.96);
                        subitem.Text = sellPrice.ToString();
                        item.SubItems.Add(subitem);

                        dicItem.Add(item.Text, item);
                        listView1.Items.Add(item);
                    }
                    buyList.Items.Add(s);

                }
                else if (temp.Contains("손절가") && temp.Contains("대응하"))
                {
                    alertList.Items.Add(s);

                }

            }
            refreshTimer.Enabled = true;
        }

        private string findItem(string str)
        {
            string[] splitStr = new string[] { "원기준매수!" };
            return Regex.Replace(str.Split(splitStr, StringSplitOptions.RemoveEmptyEntries)[0].Substring(1), @"\d", "");

        }

        private string findBuyPrice(string str)
        {
            string[] splitStr = new string[] { "원기준매수!" };
            return Regex.Replace(str.Split(splitStr, StringSplitOptions.RemoveEmptyEntries)[0], @"\D", "");
        }

        private string findSellPrice(string str)
        {
            string[] splitStr = new string[] { "1차목표가" };
            return Regex.Replace(str.Split(splitStr, StringSplitOptions.RemoveEmptyEntries)[1], @"\D", "");
        }
    }
}
